package com.googlecode.cswish.security.auth;

import java.util.HashMap;
import java.util.Map;


import org.apache.commons.lang.StringUtils;

import com.googlecode.cswish.util.FrameConstant;


public class Parameter {

	private static final String INIT_PATH = "";
	
	// cache the external parameter
	private String url;
	
	private String path;
	
	private String formAction;
	
	private Map paramter;
	
	public Parameter(String url) {
		this.url = url;
	}
	
	public Parameter(String path, Map parameter) {
		this.path = path;
		this.paramter = parameter;
	}

	public String getFormAction() {
		if (formAction == null) {
			Map parameter = getParamters();
			if (parameter != null) {
				formAction = (String) parameter.get(FrameConstant.FORM_ACTION);
			}
			if (formAction == null) {
				formAction = INIT_PATH;
			}
		}
		return (formAction == INIT_PATH) ? null : formAction;
	}

	public Map getParamters() {
		if (paramter == null) {
			int index = url.indexOf('?');
			if (index > 0) {
				String queryStr = url.substring(index + 1);
				String[] nameValues = StringUtils.split(queryStr, '&');
				paramter = new HashMap();
				for (int i = 0; i < nameValues.length; i++) {
					String nameValue = nameValues[i];
					int pos = nameValue.indexOf('=');
					String name;
					String value;
					if (pos > 0) {
						name = nameValue.substring(0, pos);
						value = nameValue.substring(pos + 1);
					} else {
						name = nameValue;
						value = "";
					}
					if (paramter.get(name) == null) {
						paramter.put(name, value);
					} else {
						// TODO: convert it to array, and put it to paramter
						
					}
				}
			} else {
				paramter = new HashMap();
			}
		}
		return paramter;
	}
	
	public String getParameter(String paramName) {
		Object theValue = getParamters().get(paramName);
		if (theValue != null) {
			String paramValue;
			if (theValue instanceof String[]) {
				paramValue = ((String[])theValue)[0];
			} else {
				paramValue = (String) theValue;
			}
			return paramValue;
		} else {
			return null;
		}
	}

	public String getPath() {
		if (path == null) {
			int index = url.indexOf('?');
			if (index > 0) {
				path = url.substring(0, index);
			} else {
				path = url;
			}
		}
		return path;
	}

	public String getUrl() {
		return url;
	}
}
